# -*- coding: utf-8 -*-
'''
Created on Nov 1, 2010

@author: HoangNamHai
'''
import datetime
import time
import sys
from suds.client import Client
from pymongo import Connection
import logging
from mongolog.handlers import MongoHandler


def getStockInfo(marketName):
    log.debug("Start getStockInfo({0})".format(marketName))
    print "Start getStockInfo({0})".format(marketName)
    ''' 0. Ngày
        1. Thông tin thị trường -> split theo |
            111.08|-1.78|11,569|16,173,668|312.667|49|71|229|C
            HNX-Index: 111.08 Thay đổi: ▼-1.78(-1.58%) Số GD: 11,569 KLGD: 16,173,668 GTGD: 312.667 ▲ 49 ■ 71 ▼ 229 Trạng thái TT: Đóng cửa
        2. Thông tin cổ phiếu -> split theo @ -> split theo |
        3. Thông tin chào mua thỏa thuận
        4. Thông tin khớp thỏa thuận
        5. Thông tin chào bán thỏa thuận
        6. Sequence num '''
    try:
        client = Client('http://banggia.tls.vn/{0}/WebService.asmx?wsdl'.format(marketName))
        lines = client.service.LoadFull(0).split('#')
        
        print lines
        
        connection = Connection('beta.mana.vn', 27017)
        db = connection['chungkhoan']
        collection = db[marketName]
        collection.save({'_id':lines[0], 'ngay':lines[0], 'thitruong':lines[1], 'cophieu':lines[2],
                         'muathoathuan':lines[3], 'khopthoathuan':lines[4], 'banthoathuan':lines[5], 'seqnum':lines[6],
                         'lastupdate':str(datetime.datetime.now()), 'timestamp':time.time()})
        
        for line in lines:
            print line
    except:
        print 'getStockInfo error'
        print sys.exc_info()[0]
        print sys.exc_info()[1]
        log.error("marketName failed: {0} || {1} >> {2}".format(marketName, sys.exc_info()[0]), sys.exc_info()[1])
        pass
    
log = logging.getLogger('ThanglongSc_Banggia')
log.setLevel(logging.DEBUG)
log.addHandler(MongoHandler.to('mongolog', 'log'))

log.debug("Start crawler ThanglongSc_Banggia")
getStockInfo('upcom')
getStockInfo('ha')
getStockInfo('ho')
log.debug("Crawler ThanglongSc_Banggia finished")

print "Đã xong", datetime.datetime.now()
sys.exit()
